package com.suns.demo;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("suns_async_producer");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        CountDownLatch latch = new CountDownLatch(5);
        Message message = null;

        for (int i = 0; i < 5; i++) {
            message = new Message("suns_async_tp_01", ("这是suns异步消息-" + i).getBytes(StandardCharsets.UTF_8));
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    // 需要注意：在此处考虑到在消息发送结果处理的时候的各种异常信息，因为客户端框架不会对此处抛出的异常做任何处理
                    System.out.println(sendResult);
                    latch.countDown();
                }

                @Override
                public void onException(Throwable e) {
                    System.err.println(e.getCause());
                    latch.countDown();
                }
            });
        }
        latch.await();
        producer.shutdown();
    }
}
